<template>
  <div>
    <div class="mt-4">
      <el-form inline>
        <el-row>
          <el-col :span="8">
            <el-form-item>
              <el-input
                  placeholder="请输入客户姓名"
                  v-model="searchKeyword"
                  clearable
                  @clear="getbedDetails"
              >
                <template #append>
                  <el-button :icon="Search" @click="getbedDetails" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-button
              @click="showAddDialog"
              type="primary"
              class="add-button"
          >
            新增
          </el-button>
        </el-row>
      </el-form>

      <div>
        <el-table :data="bedDetailsList" border stripe>
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="customerId" label="顾客ID" />
          <el-table-column label="姓名">
            <template #default="scope">
              {{ scope.row.customer?.customerName || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="年龄">
            <template #default="scope">
              {{ scope.row.customer?.customerAge || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="联系方式">
            <template #default="scope">
              {{ scope.row.customer?.contactTel || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="bedId" label="床位号" />
          <el-table-column label="床位起始日期">
            <template #default="scope">
              {{ formatDate(scope.row.startDate) }}
            </template>
          </el-table-column>
          <el-table-column label="床位结束日期">
            <template #default="scope">
              {{ formatDate(scope.row.endDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="bedDetails" label="备注" />
          <el-table-column label="操作" width="150px">
            <template #default="scope">
              <!-- 修改传递床位详情的 ID（bedId） -->
              <el-button
                  type="primary"
                  size="small"
                  @click="showEditDialog(scope.row.id)"
              >
                修改
              </el-button>
              <!-- <el-button
                  type="warning"
                  size="small"
                  @click="showTransferDialog(scope.row)"
              >
                调换
              </el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageContains.total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>

      <!-- 对话框（调整为床位详情的表单） -->
      <el-dialog
          v-model="customerDialog"
          :title="dialogTitle"
          width="40%"
          class="custom-dialog"
      >
        <el-form
            :model="curBedDetail"
            label-width="120px"
            class="custom-form"
            :rules="bedRules"
        >
          <!-- 新增/修改时选择顾客（关联 customer 表） -->
          <el-form-item label="选择顾客" prop="customerId">
            <el-select
                v-model="curBedDetail.customerId"
                placeholder="请选择顾客"
                class="form-input"
                :disabled="dialogOptType === 2"
            >
              <el-option
                  v-for="(customer, index) in availableCustomers"
                  :key="customer.id"
                  :label="`${customer.customerName}`"
                  :value="customer.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择床位" prop="bedId">
            <el-select
                v-model="curBedDetail.bedId"
                placeholder="请选择空闲床位"
                class="form-input"
                :disabled="dialogOptType === 2"
            >
              <el-option
                  v-for="bed in availableBeds"
                  :key="bed.id"
                  :label="`${bed.bedNo}`"
                  :value="bed.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="床位起始日期" prop="startDate">
            <el-date-picker
                v-model="curBedDetail.startDate"
                type="date"
                placeholder="选择日期"
                class="form-input"
                :disabled="dialogOptType === 2 && !curBedDetail.startDate"
            />
          </el-form-item>

          <el-form-item label="床位结束日期" prop="endDate">
            <el-date-picker
                v-model="curBedDetail.endDate"
                type="date"
                placeholder="选择日期"
                class="form-input"
                :disabled="dialogOptType === 2 && !curBedDetail.endDate"
            />
          </el-form-item>

          <el-form-item label="备注" prop="bedDetails">
            <el-input
                v-model="curBedDetail.bedDetails"
                class="form-input"
                type="textarea"
            />
          </el-form-item>

          <!-- 修改时显示床位号（只读） -->
          <el-form-item label="床位号" v-if="dialogOptType === 2">
            <el-input
                v-model="curBedDetail.bedId"
                class="form-input"
                disabled
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="customerDialog = false">取消</el-button>
          <el-button
              @click="handleSubmit"
              type="primary"
              class="dialog-footer-button"
          >
            {{ dialogOptType === 1 ? '新增' : '修改' }}
          </el-button>
        </template>
      </el-dialog>

      <!-- 床位调换对话框 -->
      <el-dialog
          v-model="transferDialog"
          :title="transferTitle"
          width="60%"
          class="custom-dialog"
      >
        <el-form
            :model="transferForm"
            label-width="120px"
            class="custom-form"
            :rules="transferRules"
        >
          <!-- 顾客信息 -->
          <el-form-item label="顾客姓名">
            <el-input v-model="transferForm.customerName" disabled />
          </el-form-item>

          <!-- 原床位信息 -->
          <el-form-item label="原床位">
            <el-input
                :value="`${transferForm.originalFloor}楼 ${transferForm.originalRoom}号 ${transferForm.originalBedNo}`"
                disabled
            />
          </el-form-item>

          <!-- 新楼层选择 -->
          <el-form-item label="新楼层" prop="newFloor">
            <el-select
                v-model="transferForm.newFloor"
                placeholder="请选择新楼层"
                @change="handleFloorChange"
            >
              <el-option
                  v-for="floor of uniqueFloors"
                  :key="floor"
                  :label="`${floor}楼`"
                  :value="floor"
              />
            </el-select>
          </el-form-item>

          <!-- 新房间选择 -->
          <el-form-item label="新房间" prop="newRoom">
            <el-select
                v-model="transferForm.newRoom"
                placeholder="请选择新房间"
                :disabled="!transferForm.newFloor"
                @change="handleRoomChange"
            >
              <el-option
                  v-for="room of availableRooms"
                  :key="room"
                  :label="`${room}号`"
                  :value="room"
              />
            </el-select>
          </el-form-item>

          <!-- 新床位选择 -->
          <el-form-item label="新床位" prop="newBedId">
            <el-select
                v-model="transferForm.newBedId"
                placeholder="请选择新床位"
                :disabled="!transferForm.newRoom"
                @change="handleNewBedSelect"
            >
              <el-option
                  v-for="bed of availableBedsInRoom"
                  :key="bed.id"
                  :label="bed.bedNo"
                  :value="bed.id"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <!-- 调换按钮 -->
        <template #footer>
          <el-button @click="transferDialog = false">取消</el-button>
          <el-button
              @click="handleTransferSubmit"
              type="primary"
              class="dialog-footer-button"
          >
            确认调换
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import http from '@/axios/http';
import { Plus, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 数据响应式变量
const searchKeyword = ref('');
const bedDetailsList = ref([]);
const pageNum = ref(1);
const pageSize = ref(10);
const pageContains = ref({ total: 0 });
const customerDialog = ref(false);
const dialogTitle = ref('');
const dialogOptType = ref(0); // 1=新增，2=修改
const curBedDetail = ref({
  id: null,
  customerId: null,
  startDate: null,
  endDate: null,
  bedDetails: '',
  bedId: null,
});
const availableCustomers = ref([]); // 可用顾客列表

// 新增响应式变量：可用床位列表
const availableBeds = ref([]);

// 获取可用床位（状态为空闲的床位）
const fetchAvailableBeds = async () => {
  try {
    const res = await http.post('/lyy/get_available_beds');
    if (res.data.result === 'success') {
      availableBeds.value = res.data.data;
    }
  } catch (error) {
    console.error('获取可用床位失败:', error);
  }
};

// 表单验证规则
const bedRules = reactive({
  customerId: [{ required: true, message: '请选择顾客', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择起始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  bedDetails: [{ required: true, message: '请输入备注', trigger: 'blur' }],
});

// 调换功能新增变量
const transferDialog = ref(false);
const transferTitle = ref('床位调换');
const transferForm = ref({
  bedDetailId: null, // 床位详情ID
  customerId: null,
  customerName: '',
  originalFloor: null, // 原楼层
  originalRoom: null, // 原房间号
  originalBedNo: '', // 原床位号
  newFloor: null,
  newRoom: null,
  newBedId: null,
});
const transferRules = reactive({
  newFloor: [{ required: true, message: '请选择新楼层', trigger: 'change' }],
  newRoom: [{ required: true, message: '请选择新房间', trigger: 'change' }],
  newBedId: [{ required: true, message: '请选择新床位', trigger: 'change' }],
});

// 计算属性：唯一楼层列表
const uniqueFloors = computed(() => {
  return [...new Set(availableBeds.value.map(bed => bed.floor))].sort((a, b) => a - b);
});

// 计算属性：可用房间（根据楼层过滤）
const availableRooms = computed(() => {
  if (!transferForm.value.newFloor) return [];
  return [...new Set(availableBeds.value
      .filter(bed => bed.floor === transferForm.value.newFloor)
      .map(bed => bed.roomNo))];
});

// 计算属性：可用床位（根据房间过滤，不考虑床位状态）
const availableBedsInRoom = computed(() => {
  if (!transferForm.value.newRoom) return [];
  return availableBeds.value.filter(bed =>
      bed.floor === transferForm.value.newFloor &&
      bed.roomNo === transferForm.value.newRoom
  );
});

// 楼层变化处理
const handleFloorChange = () => {
  transferForm.value.newRoom = null;
  transferForm.value.newBedId = null;
};

// 处理新床位选择
const handleNewBedSelect = (newBedId) => {
  transferForm.value.newBedId = newBedId;
};

// 根据 customer_id 获取 beddetails 数据
const getBedDetailsByCustomerId = async (customerId) => {
  try {
    const res = await http.post('/lyy/get_beddetails_by_customer_id', { customerId });
    if (res.data.result === 'success') {
      return res.data.data;
    } else {
      ElMessage.error(res.data.error);
      return null;
    }
  } catch (error) {
    console.error('获取 beddetails 数据失败:', error);
    ElMessage.error('获取 beddetails 数据失败，请重试');
    return null;
  }
};

// 显示调换对话框
const showTransferDialog = async (row) => {
  transferDialog.value = true;
  transferForm.value = {
    customerId: row.customerId,
    customerName: row.customer?.customerName || '-',
    newFloor: null,
    newRoom: null,
    newBedId: null,
  };

  // 根据 customer_id 获取 beddetails 数据
  const bedDetails = await getBedDetailsByCustomerId(row.customerId);
  if (bedDetails) {
    transferForm.value.bedDetailId = bedDetails[0].id;
    transferForm.value.originalFloor = bedDetails[0].bed?.floor;
    transferForm.value.originalRoom = bedDetails[0].bed?.roomNo;
    transferForm.value.originalBedNo = bedDetails[0].bed?.bedNo;
  }

  fetchAvailableBeds(); // 刷新可用床位
};

// 处理调换提交
const handleTransferSubmit = async () => {
  // 验证新床位是否存在
  const newBed = availableBedsInRoom.value.find(bed => bed.id === transferForm.value.newBedId);
  if (!newBed) {
    return ElMessage.error('所选床位不存在');
  }

  // 验证 bedDetailId 和 newBedId 是否存在
  if (!transferForm.value.bedDetailId || !transferForm.value.newBedId) {
    return ElMessage.error('床位详情ID和新床位ID不能为空');
  }

  try {
    // 获取当前的 beddetails 数据
    const currentBedDetails = await getBedDetailsByCustomerId(transferForm.value.customerId);
    if (!currentBedDetails) {
      return ElMessage.error('获取当前床位详情失败');
    }

    // 构造新的 beddetails 数据
    const newBedDetails = {
      ...currentBedDetails[0],
      bedId: transferForm.value.newBedId
    };

    // 打印传递的数据，检查格式
    const requestData = {
      bedDetailId: transferForm.value.bedDetailId,
      newBedId: transferForm.value.newBedId,
      newBedDetails: newBedDetails
    };
    console.log('传递的数据:', requestData);

    // 调用调换接口（需根据实际接口调整）
    const res = await http.post('/lyy/bed_transfer', requestData);
    if (res.data.success) {
      ElMessage.success('床位调换成功');
      transferDialog.value = false;
      getbedDetails(); // 刷新列表
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (error) {
    ElMessage.error('调换失败，请重试');
    console.error('调换接口错误:', error);
  }
};

// 获取床位详情
const getbedDetails = async () => {
  try {
    const res = await http.post('/lyy/get_bed_details', {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
    });
    if (res.data.result === 'success') {
      pageContains.value = res.data.data; // 提取 data 中的 total 和 list
      bedDetailsList.value = res.data.data.list;
      console.log('获取到的床位数据:', bedDetailsList.value);
    } else {
      ElMessage.error(res.data.error);
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('获取床位详情失败，请重试');
  }
};

// 获取可用顾客（未关联床位的顾客）
const fetchAvailableCustomers = async () => {
  try {
    const res = await http.post('/lyy/get_available_customers');
    console.log('接口原始响应:', res.data); // 确认数据结构
    if (res.data.result === 'success') {
      // 从 res.data.data 中获取顾客数组
      availableCustomers.value = res.data.data;
      console.log('可用顾客列表:', availableCustomers.value); // 应输出包含 customerName 的数组
    } else {
      ElMessage.error(res.data.error);
    }
  } catch (error) {
    console.error('获取可用顾客失败:', error);
    ElMessage.error('加载顾客列表失败，请重试');
  }
};

// 处理提交（新增/修改）
const handleSubmit = async () => {
  console.log('提交的 curBedDetail:', curBedDetail.value); // 检查 id 是否存在
  try {
    if (dialogOptType.value === 1) { // 新增
      await http.post('/lyy/add_bed_details', curBedDetail.value);
      ElMessage.success('新增床位详情成功');
    } else { // 修改
      await http.post('/lyy/update_bed_details', curBedDetail.value);
      ElMessage.success('修改床位详情成功');
    }
    customerDialog.value = false;
    getbedDetails();
    fetchAvailableCustomers(); // 刷新可用顾客列表
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`);
  }
};

// 显示编辑对话框（传递床位详情的 ID）
const showEditDialog = async (id) => {
  console.log('传递的 id 类型和值:', typeof id, id); // 应输出 "number 123"
  // 新增：校验 id 是否为有效数字
  if (!id || typeof id !== 'number' || isNaN(id)) {
    ElMessage.error('无效的记录 ID，请刷新后重试');
    return;
  }
  console.log("获取到的id：", id)
  try {
    dialogTitle.value = '修改床位信息';
    dialogOptType.value = 2; // 设置为修改模式
    customerDialog.value = true;
    console.log("11111111111111111111111")
    // 根据床位详情的 ID 获取床位详情数据（注意接口路径是否正确）
    const res = await http.post('/lyy/get_beddetails_by', { id }); // 假设接口正确返回数据
    console.log('接口返回数据:', res.data);
    if (res.data.result === 'success') {
      const bedDetail = res.data.data;
      console.log('bedDetail.id:', bedDetail.id); // 确保非 null/undefined
      console.log('bedDetail 结构:', bedDetail);
      // 关键修改：确保 id 正确赋值
      curBedDetail.value = {
        id: bedDetail.id, // 明确赋值 id
        customerId: bedDetail.customerId,
        startDate: bedDetail.startDate,
        endDate: bedDetail.endDate,
        bedDetails: bedDetail.bedDetails,
        bedId: bedDetail.bedId,
      };

      // 加载可用顾客和床位（可选，根据业务需求）
      await fetchAvailableCustomers();
      await fetchAvailableBeds();
    } else {
      ElMessage.error(res.data.error);
    }
  } catch (error) {
    console.error('获取编辑数据失败:', error);
    ElMessage.error('获取床位详情失败，请重试');
  }
};

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增床位信息';
  dialogOptType.value = 1;
  customerDialog.value = true;
  curBedDetail.value = { customerId: null, bedId: null }; // 初始化床位ID
  curBedDetail.value = {
    customerId: null,
    startDate: null,
    endDate: null,
    bedDetails: '',
    bedId: null,
  };
  fetchAvailableCustomers(); // 加载可用顾客
  fetchAvailableBeds(); // 加载床位
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页数量
  pageNum.value = 1; // 切换页数后重置为第 1 页
  getbedDetails(); // 重新请求数据
};

const handlePageChange = (newPage) => {
  pageNum.value = newPage; // 更新页码
  getbedDetails(); // 重新请求数据
};

// 初始化加载
onMounted(() => {
  getbedDetails();
  fetchAvailableCustomers();
  fetchAvailableBeds();
});
</script>
<style scoped>
.add-button {
  margin-left: 20px;
}

.custom-dialog {
  margin-top: 50px;
}

.custom-form .el-form-item {
  margin-bottom: 15px;
}

.el-table .is-warning {
  color: #f56c6c;
}
</style>